"""
关注公众号:Ctp接口量化
"""
import re
import time
import pandas as pd
import json
from bs4 import BeautifulSoup as bs
import random
import requests
import requests.packages.urllib3.util.ssl_
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ALL'
import Config as *
class DCTD():
    url = Config
    def __init__(self,cookie):
        # super().__init__()
        self.cookie = cookie  # 该用户登录的cookie
        self.s = requests.Session()
        self.Get_cookie()
        self.zjzh = self.Get_zjzh()
        self._url = DCTD.url['DCAPI'].format(self.userid,self.ctToken,self.utToken,self.zjzh)
    def Get_cookie(self):
        try:
            DATA = self.cookie
            A = DATA.split(";")
            for i in A:
                 b=i.split("=")
                 if b[0] == " ct":
                        # print(b[1])
                        self.ctToken = b[1]
                 if b[0] == " ut":
                        # print(b[1])
                        self.utToken = b[1]
                 if b[0] == " pi":
                        # print(b[1][:16])
                        self.userid = b[1][:16]
            return []   
        except Exception as e:
            print(u'获取数据失败：'+str(e))
            self.userid = self.Get_userid()
            return None  
    def Get_userid(self):
        try:
            headers ={"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "Accept-Encoding":"gzip, deflate",
            "Accept-Language":"zh-CN,zh;q=0.9",
            "Connection":"keep-alive",
            'Cookie': self.cookie,
            "Host": "i.eastmoney.com",
            "Referer": "i.eastmoney.com",
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
            }
            url = DCTD.url['userinfo']
            response = requests.get(headers=headers, url=url)
            return response.json()["result"]["user_id"]   
        except Exception as e:
            print(u'获取数据失败：'+str(e))
            return None  
    def Get_zjzh(self):
        try:
            url = DCTD.url['DCGET'].format(self.userid,self.ctToken,self.utToken)
            response = requests.get(url)
            return response.json()["data"][0]["zjzh"]   
        except Exception as e:
            print(u'获取数据失败：'+str(e))
            return None  
    def qrystock(self, stock_no):
        """买卖最新价
        :param stock_no: 股票代码
        """
        stock_no = str(stock_no)
        if stock_no.startswith(('50', '51', '60', '688', '73', '90', '110', '113', '132', '204', '78')):
            stock_no = '1.'+stock_no
        if stock_no.startswith(('00', '13', '18', '15', '16', '18', '20', '30', '39', '115', '1318')):
            stock_no = '0.'+stock_no
        url = 'http://push2.eastmoney.com/api/qt/stock/get?&fltt=2&fields=f120,f121,f122,f174,f175,f59,f163,f43,f57,f58,f169,f170,f46,f44,f51,f168,f47,f164,f116,f60,f45,f52,f50,f48,f167,f117,f71,f161,f49,f530,f135,f136,f137,f138,f139&secid='+stock_no
        r = self.s.get(url)
        dic = json.loads(r.text)
        return dic["data"]


    def buy(self, stock_no, price=0, amount=0):
        """买入股票
        :param stock_no: 股票代码
        :param price: 买入价格
        :param amount: 买入股数
        """
        if price == 0:
            price = self.qrystock(stock_no)["f39"]        
        stock_no = str(stock_no)
        price = str(price)
        amount = str(amount)
        if stock_no.startswith(('50', '51', '60', '688', '73', '90', '110', '113', '132', '204', '78')):
            mkcode = '1'
        if stock_no.startswith(('00', '13', '18', '15', '16', '18', '20', '30', '39', '115', '1318')):
            mkcode = '0'

        url = self._url+'spo_order&mmfx=1&mktCode=%s&stkCode=%s&price=%s&wtsl=%s' % (mkcode, stock_no, price, amount)
        r = self.s.get(url)
        print(r.text)
        print ("buy" + str(r.status_code))
        return str(r.status_code)
		
		
    def sell(self, stock_no, price=0, amount=0):
        """卖出股票
        :param stock_no: 股票代码
        :param price: 卖出价格
        :param amount: 卖出股数
        """
        if price == 0:
            price = self.qrystock(stock_no)["f19"]   
        stock_no = str(stock_no)
        price = str(price)
        amount = str(amount)
        if stock_no.startswith(('50', '51', '60', '688', '73', '90', '110', '113', '132', '204', '78')):
            mkcode = '1'
        if stock_no.startswith(('00', '13', '18', '15', '16', '18', '20', '30', '39', '115', '1318')):
            mkcode = '0'

        url = self._url+'spo_order&mmfx=2&mktCode=%s&stkCode=%s&price=%s&wtsl=%s' % (mkcode, stock_no, price, amount)
        r = self.s.get(url)
        print(r.text)
        print ("sell" + str(r.status_code))
        return str(r.status_code)	
    def qryChedan(self):    
        url = self._url+'spo_orders_cancel&reqUserid=&recIdx=0&recCnt=100'  #获取全部挂单
        r = self.s.get(url)
        dic = json.loads(r.text)  
        for position in dic["data"]:
            print("证券代码",position["stkCode"])
            print("证券名称",position["stkName"])
            print("买卖",position["mmflag"]) 
            print("委托数量",position["wtsl"])
            print("委托价格",position["wtjg"])
            print("时间",position["wtsj"])
            print("日期",position["wtrq"])
            print("合同编号",position["wth"])        
            print("="*30)
            stock_code = str(position["stkCode"])
            if stock_code.startswith(('50', '51', '60', '688', '73', '90', '110', '113', '132', '204', '78')):
                mkcode = '1'
            if stock_code.startswith(('00', '13', '18', '15', '16', '18', '20', '30', '39', '115', '1318')):
                mkcode = '0'
            url = self._url+'spo_cancel&mktCode=%s&mmfx=%s&stkCode=%s&wth=%s' % (mkcode, position["mmflag"], position["stkCode"], position["wth"])
            r = self.s.get(url)
            # dic = json.loads(r.text)
            print ("撤单" + str(r.status_code))
        # return dic
    def qryChicang(self):
        #获取持仓股票
        url = self._url+'spo_hold&reqUserid=&recIdx=0&recCnt=100'
        r = self.s.get(url)
        dic = json.loads(r.text)
        return self.data(dic["data"])     
    def qryzijin(self):
        #资金
        url = self._url+'spo_bal_info'
        r = self.s.get(url)
        dic = json.loads(r.text)
        return dic
    def 挂单(self):
        #挂单
        url = self._url+'spo_orders_cancel&reqUserid=&recIdx=0&recCnt=100'
        r = self.s.get(url)
        dic = json.loads(r.text)
        return dic        
    def qryDelegated(self):
        #当日委托
        url = self._url+'spo_orders_all&reqUserid=&recIdx=0&recCnt=100'
        r = self.s.get(url)
        dic = json.loads(r.text)
        return dic
    def qryChengjiao(self):
        #当日成交
        url = self._url+'spo_deal_today&reqUserid=&recIdx=0&recCnt=100'
        r = self.s.get(url)
        dic = json.loads(r.text)
        return dic
    def data(self,data):
        todata = []
        for pos in data:      
            data ={}
            data["编号"]= pos["fullcode"]
            data["证券代码"]= pos["stkCode"]
            data["证券名称"]= pos["stkName"]
            data["可用余额"]= pos["zqsl"]
            data["成本价"]= pos["cbj"]
            data["市价"]= pos["newPrc"]
            data["市值"]= pos["mktVal"]
            data["浮动盈亏"]= pos["fdyk"]
            # print(data)
            todata.append(data)			
        return todata

def 多账号登陆(data):
    t = []
    for i in data:
        t.append(DCTD(i))
    return t